
//
//  GGSignInVC.m
//  GGProject
//
//  Created by yuemei on 2018/5/14.
//  Copyright © 2018年 yuemei. All rights reserved.
//

#import "GGSignInVC.h"
#import "GGActionSheet.h"
static NSString *GGSignIn_Time_Cache_Key = @"GGSingnInTimeCacheKey";
@interface GGSignInVC ()<CAAnimationDelegate>
@property (weak, nonatomic) IBOutlet UIButton *singinBtn;
@property (weak, nonatomic) IBOutlet UILabel *singinLab;
@property (weak, nonatomic) IBOutlet UIView *labBgView;
@property (weak, nonatomic) IBOutlet UITextField *singinTextField;
@property(nonatomic,strong) CAShapeLayer *progressLayer;
@property (strong,nonatomic) CABasicAnimation *progressAnimation;
@property (nonatomic, assign) BOOL progressAnimOver;
@property (weak, nonatomic) IBOutlet UIView *LabBgView;
@property (nonatomic, strong) GGActionSheet *actionSheet;
@property (nonatomic, copy) void (^signinBlock)(void);
@end

@implementation GGSignInVC


- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupUI];
    self.progressAnimOver = NO;
    NSDate *singinDate = [[self readTime] lastObject];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    self.singinLab.text = [NSString stringWithFormat:@"最后一次打卡时间为:%@",[formatter stringFromDate:singinDate]];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillShow:)
                                                 name:UIKeyboardWillShowNotification
                                               object:nil];
    
    //监听当键将要退出时
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillHide:)
                                                 name:UIKeyboardWillHideNotification
                                               object:nil];
    [self.view addGestureRecognizer: [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(ViewTaped)]];
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(showSigninList)];
    self.singinLab.userInteractionEnabled = YES;
    [self.singinLab addGestureRecognizer:tap];
    
    
}
-(void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}


-(void)setupUI{
    
    
    self.singinBtn.layer.shadowOffset = CGSizeMake(1,2);
    self.singinBtn.layer.shadowColor = HEXColor(0x293D5E, 0.5).CGColor;
    self.singinBtn.layer.shadowOpacity = 1;
    self.singinBtn.layer.shadowRadius = 3;
    
    self.labBgView.layer.shadowOffset = CGSizeMake(1,2);
    self.labBgView.layer.shadowColor = HEXColor(0x000000, 0.2).CGColor;
    self.labBgView.layer.shadowOpacity = 1;
    self.labBgView.layer.shadowRadius = 3;
    
    
}

-(void)viewDidLayoutSubviews{
    UIBezierPath *bgPath = [UIBezierPath bezierPathWithArcCenter:self.singinBtn.center radius:self.singinBtn.frame.size.width/2 startAngle:- M_PI_2 endAngle:M_PI+M_PI_2 clockwise:YES];
    self.progressLayer.frame = self.singinBtn.bounds;
    self.progressLayer.path = bgPath.CGPath;
    [self.view.layer addSublayer:self.progressLayer];
}

//当键盘出现
- (void)keyboardWillShow:(NSNotification *)notification{
    
    [self animateTextField:-60];
}

//当键退出
- (void)keyboardWillHide:(NSNotification *)notification{
    [self animateTextField:-self.view.frame.origin.y];
    
}
- (void)animateTextField:(CGFloat)offY{
    
    const float movementDuration = 0.2f; // tweak as needed
    //    int movement = (up ? -movementDistance : movementDistance);
    [UIView beginAnimations: @"anim" context: nil];
    
    [UIView setAnimationBeginsFromCurrentState: YES];
    
    [UIView setAnimationDuration: movementDuration];
    
    self.view.frame = CGRectOffset(self.view.frame, 0, offY);
    
    [UIView commitAnimations];
    
}

static NSString * yearAndHourFormatStr = @"yyyy-MM-dd HH:mm:ss";
static NSString * hourFormatStr = @"HH:mm";
static NSString * yearFormatStr = @"yyyy-MM-dd";

-(void (^)(void))signinBlock{
    
    return ^(){
        [self deleteNotification];
        if (!self.singinTextField.hidden && self.singinTextField.text.length==0) {
            
            [[GGShowHUDTool sharedInstance] showInfoHudWith:@"必须输入时间"];
        }else{
            
            NSString *signinTFHandleStr = [NSString stringWithFormat:@"%@ %@:00",[self dateStrWithDate:[NSDate date] andFormat:yearFormatStr],self.singinTextField.text];
            NSDate *now = self.singinTextField.hidden?[NSDate date]:[self dateWithDateStr:signinTFHandleStr andFormat:yearAndHourFormatStr];
            NSDate *singinTime = [NSDate dateWithTimeInterval:9 * 60 * 60 sinceDate:now];
            [self writeTime:now];
            self.singinLab.text = [NSString stringWithFormat:@"最后一次打卡时间为:%@",[self dateStrWithDate:now andFormat:yearAndHourFormatStr]];
            
            
            UILocalNotification *localNotification = [[UILocalNotification alloc] init];
            localNotification.alertBody = [NSString stringWithFormat:@"今天下班时间%@ 快下班!!!",[self dateStrWithDate:singinTime andFormat:hourFormatStr]];
            localNotification.fireDate = singinTime;
            localNotification.repeatInterval = 0;
            localNotification.soundName = UILocalNotificationDefaultSoundName;
            [[UIApplication sharedApplication] scheduleLocalNotification:localNotification];
        }
    };
}


- (IBAction)singinClick:(id)sender {
    [self.progressLayer removeAnimationForKey:@"progressAnimation"];
    
    if (self.progressAnimOver == NO) {
        self.signinBlock();
        
    }
    
}

- (IBAction)signinTouchDouwn:(id)sender {
    [self.progressLayer addAnimation:self.progressAnimation forKey:@"progressAnimation"];
    
}
-(void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag{
    
        [self.progressLayer removeAnimationForKey:@"progressAnimation"];
        if(self.singinTextField.hidden == NO){
            self.progressAnimOver = YES;
        }else{
            self.progressAnimOver = flag;
        }
    
        if (flag == YES) {
            if (self.singinTextField.hidden == NO) {
                self.signinBlock();
            }
            self.singinTextField.hidden = !self.singinTextField.hidden;
            
        }
    
    
}

-(NSString *)dateStrWithDate:(NSDate *)date andFormat:(NSString *)format{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:format];
    return [formatter stringFromDate:date];
}

-(NSDate *)dateWithDateStr:(NSString *)dateStr andFormat:(NSString *)format{
    NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
    [formatter setDateFormat:format];
    return [formatter dateFromString:dateStr];
}

-(void)deleteNotification{
    NSArray *array = [UIApplication sharedApplication].scheduledLocalNotifications;
    for (UILocalNotification *local in array) {
        
        [[UIApplication sharedApplication] cancelLocalNotification:local];
        
    }
}
-(void)writeTime:(NSDate *)date{
    NSArray *dateA = [self readTime];
    NSMutableArray *arrayM = [NSMutableArray arrayWithArray:dateA];
    [arrayM addObject:date];
    if (arrayM.count > 20) {
        NSIndexSet *indexSet = [NSIndexSet indexSetWithIndexesInRange:NSMakeRange(0, arrayM.count - 20)];
        [arrayM removeObjectsAtIndexes:indexSet];
    }
    [[GGDataBase shareDataBase] setCacheWithData:arrayM Key:GGSignIn_Time_Cache_Key];
}

-(NSArray *)readTime{
    NSArray *dateA = [[GGDataBase shareDataBase] getCacheForKey:GGSignIn_Time_Cache_Key];
    return dateA;
}
- (void)ViewTaped{
    [self.view endEditing:YES];
}
-(void)showSigninList{
    [self.actionSheet showGGActionSheet];
}

-(CAShapeLayer *)progressLayer{
    if (!_progressLayer) {
        _progressLayer = [[CAShapeLayer alloc] init];
        _progressLayer.fillColor = [[UIColor clearColor] CGColor];
        _progressLayer.strokeColor = HEXColor(0x324A73, 1).CGColor;
        _progressLayer.strokeStart = 0;
        _progressLayer.strokeEnd = 0;
        _progressLayer.lineCap = kCALineCapRound;//指定线的边缘是圆的
        _progressLayer.lineJoin = kCALineCapRound;
        _progressLayer.lineWidth = 4;
    }
    return _progressLayer;
}
-(CABasicAnimation *)progressAnimation{
    if (!_progressAnimation) {
        _progressAnimation = [CABasicAnimation animationWithKeyPath:@"strokeEnd"];
        _progressAnimation.duration = 2;
        _progressAnimation.repeatCount = 1;
        _progressAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseOut];
        _progressAnimation.fromValue = @0;
        _progressAnimation.toValue = @1;
        _progressAnimation.fillMode = kCAFillModeForwards;
        _progressAnimation.removedOnCompletion = NO;
        _progressAnimation.delegate = self;
    }
    return _progressAnimation;
}
-(GGActionSheet *)actionSheet{
    
    NSMutableArray *dateArray = [NSMutableArray arrayWithArray:[self readTime]];
    NSIndexSet *indexSet = [NSIndexSet indexSetWithIndexesInRange:NSMakeRange(0, dateArray.count - 5)];
    [dateArray removeObjectsAtIndexes:indexSet];
    for (int i = 0;i < dateArray.count;++i){
        NSDate *date = dateArray[i];
        NSString *str = [self dateStrWithDate:date andFormat:yearAndHourFormatStr];
        [dateArray replaceObjectAtIndex:i withObject:str];
    }
    _actionSheet = [GGActionSheet ActionSheetWithTitleArray:dateArray andTitleColorArray:nil delegate:nil
                    ];
    //取消按钮颜色设置
    _actionSheet.cancelDefaultColor = [UIColor blueColor];
    //如果设置了选项颜色 当颜色数组和标题数组数量对不上时 多余标题使用选项默认颜色
    //如果设置了选项颜色 当颜色数组传空时，所有选项默认使用选项颜色
    //如果没设置选项颜色 数量对不上以及颜色数组为空时都使用默认黑色
    _actionSheet.optionDefaultColor = [UIColor blackColor];
    
    return _actionSheet;
}
@end
